package cn.dao;

import cn.pojo.BigClass;
import cn.util.DaoCount;
import cn.util.DaoUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jia
 * @Description
 * @date 2019-03-21-10:47
 */
public class BigClassDao {
    /**
     * 添加一个大分类
     */
    public void add(BigClass bigClass) {
        String sql = "INSERT INTO bigclass(bigName, bigText) VALUES (?, ?)";
        try (Connection connection = DaoUtil.getConnection();
             PreparedStatement ps = connection.prepareStatement(sql)) {
            ps.setString(1, bigClass.getBigName());
            ps.setString(2, bigClass.getBigText());
            ps.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除一个大分类
     */
    public void delete(int id) {
        String sql = "delete from bigclass where id = ?";
        try (Connection connection = DaoUtil.getConnection();
             PreparedStatement ps = connection.prepareStatement(sql)) {
            ps.setInt(1, id);
            ps.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改大分类
     */
    public void update(BigClass bigClass) {
        String sql = "update bigclass set bigName = ?, bigText = ? where id = ?";
        try (Connection connection = DaoUtil.getConnection();
             PreparedStatement ps = connection.prepareStatement(sql)) {
            ps.setString(1, bigClass.getBigName());
            ps.setString(1, bigClass.getBigText());
            ps.setInt(1, bigClass.getId());
            ps.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询所有大分类
     */
    public List<BigClass> getList() {
        List<BigClass> bigClassList = new ArrayList<>();
        String sql = "select * from bigclass";
        try (Connection connection = DaoUtil.getConnection();
             Statement statement = connection.createStatement()) {
            ResultSet rs = statement.executeQuery(sql);
            while (rs.next()) {
                BigClass bigClass = new BigClass();
                bigClass.setId(rs.getInt("id"));
                bigClass.setBigName(rs.getString("bigName"));
                bigClass.setBigText(rs.getString("bigText"));
                bigClassList.add(bigClass);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return bigClassList;
    }

    /**
     * 查询总记录数
     */
    public int getTotal() {
        String sql = "select count(id) from bigclass";
        return DaoCount.count(sql);
    }

}
